package cn.thoughtworks.school.configrations;

import cn.thoughtworks.school.entities.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Jwts;
import javassist.NotFoundException;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class TokenUtil {
    private static final String SECRET = "ThisIsASecret";
    private static final String TOKEN_PREFIX = "Bearer";

    public static User parseTokenToJsonObject(String token) throws Exception {
        if (Objects.isNull(token)) {
            throw new NotFoundException("Uncertified！");
        }
        token = removePrefixString(token);
        Map body = Jwts.parser().setSigningKey(SECRET.getBytes("UTF-8")).parseClaimsJws(token).getBody();
        return convertUser(body);
    }

    private static String removePrefixString(String token) {
        return token.replace(TOKEN_PREFIX + " ", "");
    }

    private static User convertUser(Map<String, Object> body) throws IOException {
        Map<String, Object> userMap = new ObjectMapper().readValue(body.get("sub").toString(), HashMap.class);
        User user = new User(userMap.get("username").toString(), (List<Integer>) userMap.get("roles"),Long.parseLong(userMap.get("id").toString()));
        return user;
    }
}
